using System.Collections.Generic;
using Game.Core;
using Game.Main.View;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

namespace Game.Manager
{
	public class UIManager : Singleton<UIManager>
	{
		public Transform canvas;

		public Transform uiLayer;

		public Camera uiCamera;

		public Camera camera;

		public EventSystem evtSystem;

		public GraphicRaycaster graphicRaycaster;

		private List<BaseView> views = new List<BaseView>();

		private PointerEventData eventData;

		private List<RaycastResult> resultList;

		public UIManager()
		{
			if (!(canvas != null))
			{
				canvas = GameObject.Find("Canvas").transform;
				canvas.GetComponent<RectTransform>().anchoredPosition = new Vector2(-20f, 5f);
				uiCamera = canvas.Find("UICamera").GetComponent<Camera>();
				uiLayer = canvas.Find("UILayer");
				graphicRaycaster = canvas.GetComponent<GraphicRaycaster>();
				evtSystem = GameObject.Find("EventSystem").GetComponent<EventSystem>();
			}
		}

		public void AddView(BaseView view)
		{
			if (view != null)
			{
				if (views.Contains(view))
				{
					views.Remove(view);
				}
				views.Add(view);
				OpenView(view);
			}
		}

		public void RemoveView(BaseView view)
		{
			if (view != null && views.Contains(view))
			{
				views.Remove(view);
			}
		}

		public Vector2 SceneToUIPoint(Vector3 point)
		{
			Vector2 localPoint = Vector2.one;
			RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas as RectTransform, point, uiCamera, out localPoint);
			return localPoint;
		}

		public bool IsPointerOverUI(Vector3 pos)
		{
			resultList = GetRaycastObjects(pos);
			return resultList.Count > 0;
		}

		public List<RaycastResult> GetRaycastObjects(Vector3 pos)
		{
			eventData = new PointerEventData(evtSystem);
			eventData.pressPosition = pos;
			eventData.position = pos;
			resultList = new List<RaycastResult>();
			graphicRaycaster.Raycast(eventData, resultList);
			return resultList;
		}

		public void OpenView(BaseView view)
		{
			CheckIsHideScene();
		}

		public void CloseView(BaseView view)
		{
			CheckIsHideScene();
		}

		public void CheckIsHideScene()
		{
			for (int i = 0; i < views.Count; i++)
			{
				if (views[i].isHideScene && views[i].IsOpen)
				{
					HideSceneAndMainView(true);
					return;
				}
			}
			HideSceneAndMainView(false);
		}

		private void HideSceneAndMainView(bool val)
		{
			if (val)
			{
				Singleton<CameraManager>.Instance.SetCameraFar(0.1f);
			}
			else
			{
				Singleton<CameraManager>.Instance.SetCameraFar();
			}
		}
	}
}
